
package logic.forms;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import logic.beans.Composition;
import logic.beans.Drug;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import controller.SEISaudeDefaultFacade;

public class DrugForm extends ElementForm<Drug> {
	private static final long serialVersionUID = 1L;
	
	@Override
	public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) {
		ActionErrors errors = new ActionErrors();
		
		if (isFieldEmpty(getElement().getScientificName())) {
			errors.add("scientificName",new ActionMessage("drug.register.error.scientificName.empty"));
		}
		
		return errors;
	}
	
	@Override
	public List<String> getEmptyPropertyNames() {
		List<String> result = new ArrayList<String>();
		
		if (isFieldEmpty(getElement().getScientificName()))
			result.add("cientificName");
		if (isFieldEmpty(getElement().getCommercialName()))
			result.add("commercialName");
		if (isFieldEmpty(getElement().getOwner()))
			result.add("owner");
		if (getElement().getCompositions().isEmpty())
			result.add("compositions");
		
		return result;
	}
	
	@Override
	public void setElementFromRequest(HttpServletRequest request) {
		SEISaudeDefaultFacade<Composition,Long> compositionFacade = SEISaudeDefaultFacade.getInstance(Composition.class);
		Set<Composition> compositionList = new HashSet<Composition>();
		String sizeParam = request.getParameter("compositionsListSize");
		for (int i = 0; i < Integer.parseInt(sizeParam == null ? "0" : sizeParam); i++) {
			String eachCompositionDescValue = request.getParameter("compositionDescription" + String.valueOf(i));
			String eachCompositionQtyValue = request.getParameter("compositionQuantity" + String.valueOf(i));
			String eachCompositionUnitValue = request.getParameter("compositionUnit" + String.valueOf(i));
			if (!eachCompositionDescValue.isEmpty() && !eachCompositionQtyValue.isEmpty()) {
				Composition theComposition = new Composition(eachCompositionDescValue,Integer.parseInt(eachCompositionQtyValue),eachCompositionUnitValue);
				List<Composition> matchingCompositions = compositionFacade.getElementsByExample(theComposition,new ArrayList<String>());
				if (matchingCompositions.isEmpty()) {
					compositionFacade.registerElement(theComposition);
				} else {
					theComposition = matchingCompositions.get(0);
				}
				compositionList.add(theComposition);
			}
		}
		getElement().setCompositions(compositionList);
	}
}
